package dao;
import vo.Message;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class Messagedao {
    public void addMessage(Message message) throws SQLException {
        Connection conn= Base.getConnection();
        String sql = "INSERT INTO messages(username, message,time) VALUES (?,?,?)";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        preparedStatement.setString(1, message.getUsername());
        preparedStatement.setString(2, message.getMessage());
        preparedStatement.setTimestamp(3, new java.sql.Timestamp(message.getTime().getTime()));
        preparedStatement.executeUpdate();
        }

    public List<Message> getAllMessages() throws SQLException {
        Connection conn= Base.getConnection();
        List<Message> messages = new ArrayList<>();
        String sql = "SELECT * FROM messages";
        PreparedStatement pst = conn.prepareStatement(sql);
        ResultSet set = pst.executeQuery();
            while (set.next()) {
                String username = set.getString("username");
                String text = set.getString("message");
                Date time=set.getDate("time");
                messages.add(new Message(username,text,time));
            }
        Base.close(conn,pst,set);
        return messages;
    }
}
